﻿using Microsoft.AspNetCore.Http;
using System.Text;

namespace SenGe.Domain.Utils
{
    /// <summary>
    /// 通用工具类
    /// </summary>
    public static class CommonUtil
    {
        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <param name="context">请求上下文</param>
        /// <returns></returns>
        public static string GetIP(HttpContext context)
        {
            string? ipv4 = context.Connection.RemoteIpAddress?.MapToIPv4()?.ToString();
            string? xForwardedFor = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            return xForwardedFor?.Length > 0 ? xForwardedFor : ipv4?.Length > 0 ? ipv4 : string.Empty;
        }

        /// <summary>
        /// 去掉字符串中的特殊字符(如表情字符)
        /// 仅保留中文字符，大小写英文字符，数字，标点符号和换行符
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string RemoveSpecialChars(string input)
        {
            StringBuilder result = new StringBuilder();
            foreach (char c in input)
            {
                if ((c >= '\u4e00' && c <= '\u9fa5') || // 中文字符
                    (c >= 'a' && c <= 'z') ||           // 小写字母
                    (c >= 'A' && c <= 'Z') ||           // 大写字母
                    (c >= '0' && c <= '9') ||           // 数字
                    char.IsPunctuation(c) ||            // 标点符号
                    c == '\n' || c == '\r')             // 换行符
                {
                    result.Append(c);
                }
            }
            return result.ToString();
        }
    }
}
